﻿using Abp.Application.Services.Dto;
using Abp.Domain.Repositories;
using DHJ.Cost.ImportRecord.Dto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using DHJ.Cost.Excel;


namespace DHJ.Cost.ImportRecord
{
    public class ImportRecordAppService : CostAppServiceBase,IImportRecordAppService
    {
        private readonly IRepository<ExcelData, Guid> _excelDataRepository;
        private readonly IRepository<ExcelItemData, Guid> _excelItemDataRepository;


        public ImportRecordAppService(
            IRepository<ExcelData, Guid> excelDataRepository,
            IRepository<ExcelItemData,Guid> excelItemDataRepository

        )
        {
            _excelDataRepository = excelDataRepository;
            _excelItemDataRepository = excelItemDataRepository;

        }

        public async Task<ListResultDto<ExcelCellDto>> GetImportExcelData(Guid id)
        {
            var items = await _excelItemDataRepository.GetAll().Where(p => p.ExcelDataId == id).ToListAsync();

            return new ListResultDto<ExcelCellDto>(items.SelectMany(e => e.Cells).Select(c => new ExcelCellDto()
            {
                Cell = c.Cell,
                Value = c.Value
            }).ToList());

        }

        public async Task<List<ImportRecordDto>> GetImportRecord(ImportRecordInput input)
        {
            try
            {
                var query = _excelDataRepository.GetAll();
                query = query
                    .Where(p => p.Time.Month == DateTime.Now.Month && p.Time.Year == DateTime.Now.Year&&p.Type==(ExcelType)input.TypeId);
                
                var totalCount = await query.CountAsync();
                var importRecord = await query
                    .ToListAsync();
              
              
                var importRecordListDto = ObjectMapper.Map<List<ImportRecordDto>>(importRecord);
                return importRecordListDto;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
    }
}
